const {
  app,
  BrowserWindow,
  dialog // 调用原生对话框的模块
} = require('electron')
const fs = require('fs')
let windows = new Set() // 窗口储存队列
const creatWindow = exports.creatWindow = () => {
  let mainWindow = null
  let x = 0
  let y = 0
  let focusWinodw = BrowserWindow.getFocusedWindow()
  if (focusWinodw) {
    let [cx, cy] = focusWinodw.getPosition()
    x = cx + 10
    y = cy + 10
  }
  mainWindow = new BrowserWindow({
    x,
    y,
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    },
    show: false // 当首次创建窗口的时候，先将它隐藏起来
  })
  mainWindow.webContents.loadFile('./index.html')
  mainWindow.once('ready-to-show', () => {
    mainWindow.show() // DOM 就绪之后展示窗口
  })
  mainWindow.on('closed', () => {
    windows.delete(mainWindow)
    // mainWindow = null
  })
  windows.add(mainWindow)
  return mainWindow
}


app.on('ready', () => {
  creatWindow()
})

// 监听退出事件   并
app.on('window-all-closed', () => {
  if (process.platform === 'darwin') { // macOs 不退出，直接返回
    // 在没有窗口时候打开一个窗口 macOS
    app.on('activate', (event, hasVisibleWindows) => {
      if (!hasVisibleWindows) {
        creatWindow()
      }
    })
    return
  }
  app.quit()
})


exports.getFileFromUser = function (targetWindow) {
  const files = dialog.showOpenDialogSync(targetWindow, {
    properties: ['openFile'],
    filters: [{
        name: 'Text Files',
        extensions: ['txt']
      },
      {
        name: 'Markdown Files',
        extensions: ['md', 'markdown']
      }
    ]
  })
  if (!files) {
    return
  }
  const file = files[0]
  openFile(targetWindow, file)
}


const openFile = exports.openFile = (targetWindow, file) => {
  const content = fs.readFileSync(file).toString()
  targetWindow.webContents.send('file-opened', file, content)
}